import '@pnp/common';
import '@pnp/odata';
import '@pnp/logging';
import { sp } from '@pnp/sp';
import '@pnp/sp/webs';
import '@pnp/sp/lists';
import '@pnp/sp/items';
import '@pnp/sp/search';
import '@pnp/sp/attachments';
import '@pnp/sp/files';
import '@pnp/sp/folders';
import '@pnp/sp/site-users/web';
import { ISearchQuery, SearchResults, SearchQueryBuilder } from '@pnp/sp/search';
import { ICamlQuery } from '@pnp/sp/lists';
import { Guid } from '@microsoft/sp-core-library';
import { ISiteUserInfo } from '@pnp/sp/site-users/types';
import { split } from 'lodash';
import { Folder } from '@pnp/sp/folders';
import * as pnp from '@pnp/sp';
import { CAMLFilter, CAMLCompare, CamlQuery, CamlParam, CamlOrderBy, SPDataType } from './CAMLHelper';
import { ListGUID } from './ListGuid';
import { dynamicsService } from '../../../../services/services';
import Item from 'antd/lib/list/Item';
import { isArray } from '@pnp/common';
const GuidName = [
  {
    name: 'StandingBook',
    guid: '9e17e4f9-4654-4b73-818d-7fb97ce4e5f0',
    listname: 'StandingBook'
  },
  {
    name: 'CaseManagement',
    guid: 'ee8fdb8e-e442-438c-940f-d6d9ce1cdc43',
    listname: 'CaseManagement'
  },
  {
    name: 'Regulations',
    guid: 'abeea6fa-2ae7-4c14-b4af-3774ae35067f',
    listname: 'Regulations'
  },
]
export default class Api {
  public static async _searchAllFiles(docTypes: string[], keyWords: string): Promise<any[]> {
    let result: any[] = [];

    //合同所有有权限数据    列表
    let contractItems: any[] = [];
    let contractPetitionItems: any[] = [];

    //规章制度所有有权限数据    列表
    let regulationsItems: any[] = [];
    let regulationsPetitionItems: any[] = [];

    //案件管理所有有权限数据    列表
    let caseManagementItems: any[] = [];

    //判断要查询的库的对应的列表需要有
    for (let i = 0; i < docTypes.length; i++) {
      const doc = docTypes[i];
      switch (doc) {
        case 'Contract':
          contractItems = await Api._getListData({ ListGUID: ListGUID.StandingBook });
          
          contractItems = await this._getPermissionData(ListGUID.StandingBook, contractItems);
          
          break;
        case 'ContractPetition':
          contractPetitionItems = await Api._getListData({ ListGUID: ListGUID.Petition });
          contractPetitionItems = await this._getPermissionData(ListGUID.Petition, contractPetitionItems);

          let clearContractPetition = contractPetitionItems.filter((ele, index) => ele.ItemBelong == 0);
          contractPetitionItems = clearContractPetition;
          break;

        case 'Regulations':
          regulationsItems = await Api._getListData({ ListGUID: ListGUID.Regulations });
          regulationsItems = await this._getPermissionData(ListGUID.Regulations, regulationsItems);
          break;
        case 'RegulationsPetition':
          regulationsPetitionItems = await Api._getListData({ ListGUID: ListGUID.Petition });
          regulationsPetitionItems = await this._getPermissionData(ListGUID.Petition, regulationsPetitionItems);

          let clearRegulationsPetition = regulationsPetitionItems.filter((ele, index) => ele.ItemBelong == 1);
          regulationsPetitionItems = clearRegulationsPetition;
          break;

        case 'CaseManagement':
          caseManagementItems = await Api._getListData({ ListGUID: ListGUID.CaseManagement });
          caseManagementItems = await this._getPermissionData(ListGUID.CaseManagement, caseManagementItems);
          break;

        default:
          break;
      }
    }

    let keys = keyWords.split(' ');

    for (let i = 0; i < docTypes.length; i++) {
      const doc = docTypes[i];

      switch (doc) {
        //搜合同
        case 'Contract':
          //合同重要性   合同期限   合同性质  我方 相对方

          for (let index = 0; index < keys.length; index++) {
            const keyWord = keys[index];
            if (keyWord == '') {
              continue;
            }

            //查询列表记录
            for (let i = 0; i < contractItems.length; i++) {
              const item = contractItems[i];
              let needAdd = {
                DocType: '',
                ID: 0,
                Title: '', //标题、编号
                ContractName: '', //合同编号、合同名称（件名）
                ContractSignificance: '', //合同重要性
                ContractDeadline: '', //合同期限
                ContractNature: '', //合同性质
                Our: '', //我方
                Counterparty: '', //相对方
                FileAddress: '', //文件保存路径
                sinsei_code: '', //申请书序列号
                FileObj: [] //附件
              };

              //判断有无已添加的记录（同时满足多个搜索条件，不重复添加）
              let findResult = result.filter((ele, index) => ele.DocType == 'Contract' && ele.ID == item.ID);
              if (findResult && findResult != null && findResult.length > 0) {
                continue;
              }
              
              
              
              
              
              
              

              if (
                (item.Title != null && `${item.Title}`.indexOf(keyWord) > -1) ||
                (item.ContractName != null && `${item.ContractName}`.indexOf(keyWord) > -1) ||
                (item.ContractSignificance != null && `${item.ContractSignificance}`.indexOf(keyWord) > -1) ||
                (item.ContractDeadline != null && `${item.ContractDeadline}`.indexOf(keyWord) > -1) ||
                (item.Our != null && `${item.Our}`.indexOf(keyWord) > -1) ||
                (item.Counterparty != null && `${item.Counterparty}`.indexOf(keyWord) > -1) ||
                (item.ContractNature != null && `${item.ContractNature}`.indexOf(keyWord) > -1)
              ) {
                needAdd.DocType = 'Contract';
                needAdd.ID = item.ID;
                (needAdd.Title = item.Title), (needAdd.ContractName = item.ContractName);
                needAdd.ContractSignificance = item.ContractSignificance;
                needAdd.ContractNature = item.ContractNature;
                (needAdd.ContractDeadline = item.ContractDeadline), (needAdd.Our = item.Our);
                needAdd.Counterparty = item.Counterparty;
                needAdd.FileAddress = item.FileAddress;
                needAdd.sinsei_code = '';
                result.push(needAdd);
              }
            }
          }

          //处理附件
          let contractFiles = await this._searchItemDocFiles(keyWords, 'Contract');

          if (contractFiles.length > 0) {
            //筛掉没权限的查询结果

            contractFiles.forEach(element => {
              let webUrl = element.path;
              let findFile = contractItems.filter(p => webUrl.indexOf(p.FileAddress) > -1);
              if (findFile && findFile.length > 0) {
                //现有记录有对应的库文件的权限 //若有：只会找到一个
                let currentFindFile = findFile[0];

                //查看之前list中是否有关联的记录
                let findItem = result.filter(p => p.ID == currentFindFile.ID && p.DocType == 'Contract');
                if (findItem && findItem.length > 0) {
                  let currentFindItem = findItem[0];
                  currentFindItem.FileObj.push(element);
                } else {
                  //总的结果集中没有，需要单独添加这条记录
                  let needAdd = {
                    DocType: 'Contract',
                    ID: currentFindFile.ID,
                    Title: currentFindFile.Title, //标题、编号
                    ContractName: currentFindFile.ContractName, //合同编号、合同名称（件名）
                    ContractSignificance: currentFindFile.ContractSignificance, //合同重要性
                    ContractDeadline: currentFindFile.ContractDeadline, //合同期限
                    ContractNature: currentFindFile.ContractNature, //合同性质
                    Our: currentFindFile.Our, //我方
                    Counterparty: currentFindFile.Counterparty, //相对方
                    FileAddress: currentFindFile.FileAddress, //文件保存路径
                    sinsei_code: '', //申请书序列号
                    FileObj: [] //附件
                  };
                  needAdd.FileObj.push(element);
                  result.push(needAdd);
                }
              }
            });
          }
          break;

        //搜合同申请书
        case 'ContractPetition':
          for (let index = 0; index < keys.length; index++) {
            const keyWord = keys[index];
            if (keyWord == '') {
              continue;
            }
            //保密程度，到期时间   对方公司名称
            //查询列表记录
            for (let i = 0; i < contractPetitionItems.length; i++) {
              const item = contractPetitionItems[i];
              let needAdd = {
                DocType: '',
                ID: 0,
                secrecy: '', //保密程度
                expire_date: '', //到期时间
                company_name: '', //对方公司名称
                FileObj: [] //附件
              };

              //判断有无已添加的记录（同时满足多个搜索条件，不重复添加）
              let findResult = result.filter((ele, index) => ele.DocType == 'ContractPetition' && ele.ID == item.ID);
              if (findResult && findResult != null && findResult.length > 0) {
                continue;
              }

              if (
                (item.secrecy && `${item.secrecy}`.indexOf(keyWord) > -1) ||
                (item.expire_date && `${item.expire_date}`.indexOf(keyWord) > -1) ||
                (item.company_name && `${item.company_name}`.indexOf(keyWord) > -1)
              ) {
                needAdd.DocType = 'ContractPetition';
                needAdd.ID = item.ID;
                needAdd.secrecy = item.secrecy;
                needAdd.expire_date = item.expire_date;
                needAdd.company_name = item.company_name;

                result.push(needAdd);
              }
            }
          }

          //处理附件

          let contractPetitionFiles = await this._searchItemDocFiles(keyWords, 'ContractPetition');

          if (contractPetitionFiles.length > 0) {
            //筛掉没权限的查询结果
            contractPetitionFiles.forEach(element => {
              //SRUrls :/ContractLib/2022/CESHI/CESHI2022001-0/
              let webUrl = element.path; //"https://yuchentech.sharepoint.com/sites/zhuhuaHT/ContractLib/2022/CESHI/CESHI2022001-0/合同导出 (1).csv"

              //从webUrl中 中查找有申请书记录（过滤后有权限的记录）/sites/zhuhuaHT/xxxx没有以上，有的话，展示
              let findFile = contractPetitionItems.filter(
                p =>
                  p.SRUrls != null && p.SRUrls != '' && p.SRUrls != undefined && webUrl.toLowerCase().indexOf(p.SRUrls.toLowerCase()) > -1
              );
              if (findFile && findFile.length > 0) {
                //现有记录有对应的库文件的权限 //若有：只会找到一个
                let currentFindFile = findFile[0];

                //查看之前list中是否有关联的记录
                let findItem = result.filter(p => p.ID == currentFindFile.ID && p.DocType == 'ContractPetition');
                if (findItem && findItem.length > 0) {
                  let currentFindItem = findItem[0];
                  currentFindItem.FileObj.push(element);
                } else {
                  //总的结果集中没有，需要单独添加这条记录
                  let needAdd = {
                    DocType: 'ContractPetition',
                    ID: currentFindFile.ID,
                    secrecy: currentFindFile.secrecy,
                    expire_date: currentFindFile.expire_date,
                    company_name: currentFindFile.company_name,
                    FileObj: [] //附件 //考虑查出来的是文件夹,可以考虑去掉或者直接绑定到页面都可以
                  };
                  needAdd.FileObj.push(element);
                  result.push(needAdd);
                }
              }
            });
          }
          break;

        //搜规章制度
        case 'Regulations':
          //法务审核编号 规定名称
          for (let index = 0; index < keys.length; index++) {
            const keyWord = keys[index];
            if (keyWord == '') {
              continue;
            }

            //查询列表记录
            for (let i = 0; i < regulationsItems.length; i++) {
              const item = regulationsItems[i];
              let needAdd = {
                DocType: '',
                ID: 0,
                Title: '', //法务审核编号
                RegulationsName: '', //规定名称
                FileObj: [] //附件
              };

              //判断有无已添加的记录（同时满足多个搜索条件，不重复添加）
              let findResult = result.filter((ele, index) => ele.DocType == 'Regulations' && ele.ID == item.ID);
              if (findResult && findResult != null && findResult.length > 0) {
                continue;
              }

              //合同编号、合同名称（件名） 合同重要性   合同期限   合同性质  我方 相对方
              if (
                (item.Title && `${item.Title}`.indexOf(keyWord) > -1) ||
                (item.RegulationsName && `${item.RegulationsName}`.indexOf(keyWord) > -1)
              ) {
                needAdd.DocType = 'Regulations';
                needAdd.ID = item.ID;
                (needAdd.Title = item.Title), (needAdd.RegulationsName = item.RegulationsName);

                result.push(needAdd);
              }
            }
          }

          //处理附件
          let regulationsFiles = await this._searchItemDocFiles(keyWords, 'Regulations');

          if (regulationsFiles.length > 0) {
            //筛掉没权限的查询结果

            regulationsFiles.forEach(element => {
              let webUrl = element.path;

              let findFile = regulationsItems.filter(p => webUrl.indexOf(p.FileAddress) > -1);
              if (findFile && findFile.length > 0) {
                //现有记录有对应的库文件的权限 //若有：只会找到一个
                let currentFindFile = findFile[0];

                //查看之前list中是否有关联的记录
                let findItem = result.filter(p => p.ID == currentFindFile.ID && p.DocType == 'Regulations');
                if (findItem && findItem.length > 0) {
                  let currentFindItem = findItem[0];
                  currentFindItem.FileObj.push(element);
                } else {
                  //总的结果集中没有，需要单独添加这条记录
                  let needAdd = {
                    DocType: 'Regulations',
                    ID: currentFindFile.ID,
                    Title: currentFindFile.Title, //标题、编号
                    RegulationsName: currentFindFile.RegulationsName,
                    FileObj: [] //附件 //考虑查出来的是文件夹,可以考虑去掉或者直接绑定到页面都可以
                  };
                  needAdd.FileObj.push(element);
                  result.push(needAdd);
                }
              }
            });
          }
          break;

        //搜规章制度申请书
        case 'RegulationsPetition':
          for (let index = 0; index < keys.length; index++) {
            const keyWord = keys[index];
            if (keyWord == '') {
              continue;
            }
            //保密程度，到期时间   对方公司名称
            //查询列表记录
            for (let i = 0; i < regulationsPetitionItems.length; i++) {
              const item = regulationsPetitionItems[i];
              let needAdd = {
                DocType: '',
                ID: 0,
                secrecy: '', //保密程度
                expire_date: '', //到期时间
                company_name: '', //对方公司名称
                FileObj: [] //附件
              };

              //判断有无已添加的记录（同时满足多个搜索条件，不重复添加）
              let findResult = result.filter((ele, index) => ele.DocType == 'RegulationsPetition' && ele.ID == item.ID);
              if (findResult && findResult != null && findResult.length > 0) {
                continue;
              }

              if (
                (item.secrecy && `${item.secrecy}`.indexOf(keyWord) > -1) ||
                (item.expire_date && `${item.expire_date}`.indexOf(keyWord) > -1) ||
                (item.company_name && `${item.company_name}`.indexOf(keyWord) > -1)
              ) {
                needAdd.DocType = 'RegulationsPetition';
                needAdd.ID = item.ID;
                needAdd.secrecy = item.secrecy;
                needAdd.expire_date = item.expire_date;
                needAdd.company_name = item.company_name;

                result.push(needAdd);
              }
            }
          }

          //处理附件
          let regulationsPetitionFiles = await this._searchItemDocFiles(keyWords, 'RegulationsPetition');

          if (regulationsPetitionFiles.length > 0) {
            //筛掉没权限的查询结果
            regulationsPetitionFiles.forEach(element => {
              //"https://yuchentech.sharepoint.com/sites/zhuhuaHT/ContractLib/2022/CESHI/CESHI2022001-0/合同导出 (1).csv"
              //sites/zhuhuaHT/ContractLib/2022/CESHI/CESHI2022001-0/合同导出 (1).csv""
              let webUrl = element.path; //.replace(ListGUID.Domain, '');
              let a: string = '';
              //从申请书记录中（过滤后有权限的记录）/sites/zhuhuaHT/xxxx 中查找有没有以上webUrl，有的话，展示
              let findFile = regulationsPetitionItems.filter(
                p =>
                  p.SRUrls != null && p.SRUrls != '' && p.SRUrls != undefined && webUrl.toLowerCase().indexOf(p.SRUrls.toLowerCase()) > -1
              );
              if (findFile && findFile.length > 0) {
                //现有记录有对应的库文件的权限 //若有：只会找到一个
                let currentFindFile = findFile[0];

                //查看之前list中是否有关联的记录
                let findItem = result.filter(p => p.ID == currentFindFile.ID && p.DocType == 'RegulationsPetition');
                if (findItem && findItem.length > 0) {
                  let currentFindItem = findItem[0];
                  currentFindItem.FileObj.push(element);
                } else {
                  //总的结果集中没有，需要单独添加这条记录
                  let needAdd = {
                    DocType: 'RegulationsPetition',
                    ID: currentFindFile.ID,
                    secrecy: currentFindFile.secrecy,
                    expire_date: currentFindFile.expire_date,
                    company_name: currentFindFile.company_name,
                    FileObj: [] //附件 //考虑查出来的是文件夹,可以考虑去掉或者直接绑定到页面都可以
                  };
                  needAdd.FileObj.push(element);
                  result.push(needAdd);
                }
              }
            });
          }
          break;

        //案件管理
        case 'CaseManagement':
          //案件概要 所属公司
          for (let index = 0; index < keys.length; index++) {
            const keyWord = keys[index];
            if (keyWord == '') {
              continue;
            }

            //查询列表记录
            for (let i = 0; i < caseManagementItems.length; i++) {
              const item = caseManagementItems[i];
              let needAdd = {
                DocType: '',
                ID: 0,
                CaseSummary: '', //案件概要
                BelongsCompany: '', //所属公司
                FileObj: [] //附件
              };

              //判断有无已添加的记录（同时满足多个搜索条件，不重复添加）
              let findResult = result.filter((ele, index) => ele.DocType == 'CaseManagement' && ele.ID == item.ID);
              if (findResult && findResult != null && findResult.length > 0) {
                continue;
              }

              if (
                (item.CaseSummary && `${item.CaseSummary}`.indexOf(keyWord) > -1) ||
                (item.BelongsCompany && `${item.BelongsCompany}`.indexOf(keyWord) > -1) ||
                (item.CaseName && `${item.CaseName}`.indexOf(keyWord) > -1)
              ) {
                needAdd.DocType = 'CaseManagement';
                needAdd.ID = item.ID;
                needAdd.CaseSummary = item.CaseSummary;
                needAdd.BelongsCompany = item.BelongsCompany;
                result.push(needAdd);
              }
            }
          }

          //处理附件

          let caseManagementFiles = await this._searchItemDocFiles(keyWords, 'CaseManagement');

          if (caseManagementFiles.length > 0) {
            //筛掉没权限的查询结果

            caseManagementFiles.forEach(element => {
              let webUrl = element.path;
              let findFile = caseManagementFiles.filter(p => webUrl.indexOf(p.FileAddress) > -1);
              if (findFile && findFile.length > 0) {
                //现有记录有对应的库文件的权限 //若有：只会找到一个
                let currentFindFile = findFile[0];

                //查看之前list中是否有关联的记录
                let findItem = result.filter(p => p.ID == currentFindFile.ID && p.DocType == 'CaseManagement');
                if (findItem && findItem.length > 0) {
                  let currentFindItem = findItem[0];
                  currentFindItem.FileObj.push(element);
                } else {
                  //总的结果集中没有，需要单独添加这条记录
                  let needAdd = {
                    DocType: 'CaseManagement',
                    ID: currentFindFile.ID,
                    CaseSummary: currentFindFile.CaseSummary,
                    BelongsCompany: currentFindFile.BelongsCompany,
                    FileObj: [] //附件 //考虑查出来的是文件夹,可以考虑去掉或者直接绑定到页面都可以
                  };
                  needAdd.FileObj.push(element);
                  result.push(needAdd);
                }
              }
            });
          }
          break;

        // //搜其他（通用文档库）TODO：如何确定范围？
        case 'Other':
          //案件概要 所属公司
          for (let index = 0; index < keys.length; index++) {
            const keyWord = keys[index];
            if (keyWord == '') {
              continue;
            }
          }

          //处理附件

          let otherFiles = await this._searchItemDocFiles(keyWords, 'Other');

          if (otherFiles.length > 0) {
            //筛掉没权限的查询结果:TODO:由于没有列表配置，这里如何筛选？
            let needAdd = {
              DocType: 'Other',
              ID: 0,
              FileObj: [] //附件 //考虑查出来的是文件夹,可以考虑去掉或者直接绑定到页面都可以
            };
            otherFiles.forEach(element => {
              needAdd.FileObj.push(element);
            });
            result.push(needAdd);
          }
          break;
        default:
          break;
      }
    }
    return result;
  }

  //过滤每一个列表的记录
  private static async _searchItemDocFiles(keyWords: string, doclibidentification: string): Promise<any[]> {
    let objFiles = [];
    let keys = keyWords.split(' ');
    let searchKeyArr: string[] = [];
    for (let index = 0; index < keys.length; index++) {
      const keyWord = keys[index];
      if (keyWord == '') {
        continue;
      }

      let apiData = await dynamicsService.getFileContentByCSOMApi(keyWord, doclibidentification);

      if (apiData && apiData.data && apiData.data.length > 0) {
        for (let i = 0; i < apiData.data.length; i++) {
          const f = apiData.data[i];
          objFiles.push(f);
        }
      }
    }

    return objFiles;
  }

  public static async _getPermissionData(listguid: string, allData: any[]): Promise<any[]> {
    let result: any[] = [];
    if (allData) {
      if (allData.length == 0) {
        return allData;
      }
    } else {
      return allData;
    }

    let currentUser = await Api._getcurrentUser();
    let currentEmail = currentUser.Email;
    let p1 = await Api.GetUserProperties(currentEmail);
    let vDep = '';
    let props = p1.UserProfileProperties;
    if (props && props.length > 0) {
      for (let i = 0; i < props.length; i++) {
        const element = props[i];
        if (element.Key == 'Department') {
          vDep = element.Value;
          break;
        }
      }
    }
      //若用角色控制，则此处判断时应取出所属角色是否为包含定义好的角色
      let isFW: boolean = vDep == '法务部' || vDep == '法務部';



    //部长及以上，带部门（人员带着部门）--理应包含总经理（总经理==董事长），但总经理（董事长）没部门，需要从权限配置，配置所要查看公司 配置All
    let leaderUpers: string[] = ['部长', '副总经理', '总监', '本部长', '副董事长', '总经理', '执行总经理', '副总经理'];
    let caseLeader:string[]=['部长','副部长','科长'];
    let isCaseLeader:boolean=false;

    //是否为部长
    let isLeader: boolean = false;
    if (props && props.length > 0) {
      for (let i = 0; i < props.length; i++) {
        const element = props[i];
        if (element.Key == 'Title') {
          let dv = element.Value;
          if (dv && dv != null && dv != '') {
            let indexFind = leaderUpers.indexOf(dv);
            isLeader = indexFind > -1;
          }
        if(dv&&dv!=null&&dv!='')
        {
            let indexCaseFind=caseLeader.indexOf(dv);
            if(isFW&&indexCaseFind>-1)
            {
        isCaseLeader=true;

            }
         

        }

          break;
        }
      }
    }

    //为防止后续内存循环频繁请求SharePoint Api，此处先抓取配置

    //映射后的FL部门（供领导筛选）
    let mapFLDepartments = [];

    //供个人筛选
    let AAD_FL_DepartmentsItems = [];
    AAD_FL_DepartmentsItems = await this._getModel({ Guid: ListGUID.FLAD });
    if (!AAD_FL_DepartmentsItems) {
      AAD_FL_DepartmentsItems = [];
    }

    if (isLeader) {
      let userCode = ''; //当前登录用户的userCode

      if (currentEmail && currentEmail != '' && currentEmail != null) {
        let userCodeArr = currentEmail.split('@');
        if (userCodeArr && userCodeArr.length > 1) {
          userCode = userCodeArr[0].toLowerCase();
        }
      }

      for (let depIndex = 0; depIndex < AAD_FL_DepartmentsItems.length; depIndex++) {
        const dep = AAD_FL_DepartmentsItems[depIndex];

        let findItem: boolean = false;

        //先找人是否匹配了
        if (dep.UserAccount && dep.UserAccount != null && dep.UserAccount != '') {
          let itemCodeArr = dep.UserAccount.split('@');
          if (itemCodeArr && itemCodeArr.length > 1) {
            let itemCode = itemCodeArr[0].toLowerCase();

            if (itemCode && itemCode != '' && itemCode == userCode) {
              findItem = true;
            }
          }
        }

        if (!findItem) {
          //人没匹配到，找部门是否能匹配上
          if (dep.AADDepartmentName && dep.AADDepartmentName != null && dep.AADDepartmentName != '') {
            if (dep.AADDepartmentName == vDep) {
              findItem = true;
            }
          }
        }

        //人员或者部门能从配置表中找到配置关系的部门或者人员，则添加此条记录
        if (findItem) {
          mapFLDepartments.push(dep);
        }
      }

      //UserAccount 用户邮箱
      //AADDepartmentName
      //FLDepartmentName
      //Title  公司简称
    }

    //所有AAD用户  AADUsers
    let jsonAADUsers = sessionStorage.getItem('AADUsers');
    let AADUsers = [];

    if (jsonAADUsers) {
      AADUsers = JSON.parse(jsonAADUsers);
    }

  
    //不是法务部，需要处理权限

    /*
权限计算说明：
  
    1、所有人默认都不用配置权限，都按照是否是法务部（按照AD中所属部门）来，以下为默认说明
        默认说明：当 当前人员未配置任何权限时（包括不配置角色、不配置人员、不配置角色人员关系、不配置数据权限关系）
            1）合同列表： 法务部可见所有，其他部门不可见
            2）规章制度： 法务部可见所有，其他部门不可见
            3）合同申请书（FL合同）：法务部可见所有，其他部门不可见
            4）规章申请书（FL规章）：所有人员都可见
            5）案件管理：见第3条说明
    2、如果一旦给某人在相应的列表配置了数据，则在对应的列表只能看配置的数据，其他的列表不受影响（遵循第一条的默认说明）
    3、对于特殊的案件管理列表遵循以下规则，
        1）无论是否配置，全员都可见保密为否的
        2）如果给某人配置了某公司的可见性，则该人员在案件管理中，除保密为否的可见外，保密为是的按照配置的来限制。


*/

    //是否配置过合同列表 数据权限
    let configStandingBookPermission: boolean = false;
    //是否配置过规章制度 数据权限
    let configRegulationsPermission: boolean = false;
    //是否配置过合同申请书 数据权限
    let configContractPetitionPermission: boolean = false;
    //是否配置过规章制度申请书 数据权限
    let configRegulationsPetitionPermission: boolean = false;
    //是否配置过案件管理 数据权限
    let configCaseManagementPermission: boolean = false;
    let dataPermissions = [];
    let sPermission = sessionStorage.getItem('userDataPermissions');
    if (sPermission) {
      dataPermissions = JSON.parse(sPermission);
      if (dataPermissions && dataPermissions.length > 0) {
        switch (listguid) {
          //合同台账权限过滤
          case ListGUID.StandingBook:
            let findStandingBook = dataPermissions.filter((item, index) => item.scopeName == 'Contract');
            if (findStandingBook && findStandingBook.length > 0) {
              configStandingBookPermission = true;
              allData.forEach(item => {
                //当前记录所属公司
                let _thisBelongsCompany = item.BelongsCompany;

                //查找有无该公司的权限限定，有的话，只有一个,API接口返回时已经做了权限计算了
                // user - 表  -公司 -时间
                let findApiRecord = findStandingBook.filter((ele, index) => ele.company == _thisBelongsCompany);
                if (findApiRecord && findApiRecord.length > 0) {
                  let _currentRecord = findApiRecord[0];
                  let itemCreated: Date = new Date(item.Created);
                  let beginTime: Date = new Date(_currentRecord.setBeginTime + 'Z');
                  let endTime: Date = new Date(_currentRecord.setEndTime + 'Z');
                  if (itemCreated >= beginTime && itemCreated <= endTime) {
                    result.push(item);
                  }
                } else {
                  //若没有找到该公司的配置，尝试获取是否有配置了 所有公司的记录 All
                  let findAllRecord = findStandingBook.filter((eleAll, index) => eleAll.company == 'All');
                  if (findAllRecord && findAllRecord.length > 0) {
                    let _currentAllRecord = findAllRecord[0];
                    let itemCreated: Date = new Date(item.Created);
                    let beginTime: Date = new Date(_currentAllRecord.setBeginTime + 'Z');
                    let endTime: Date = new Date(_currentAllRecord.setEndTime + 'Z');
                    if (itemCreated >= beginTime && itemCreated <= endTime) {
                      result.push(item);
                    }
                  }
                  //TODO：如果用户在权限配置过程中需要 配置“当前公司”，则这里判断，如果有“当前公司”则此处取到当前公司，比如AAA，则p=>p.company=="AAA"
                }
              });
            }
            break;
          //规章制度 权限过滤
          case ListGUID.Regulations:
            let findRegulationsList = dataPermissions.filter((item, index) => item.scopeName == 'Regulations');

            if (findRegulationsList && findRegulationsList.length > 0) {
              configRegulationsPermission = true;
              allData.forEach(item => {
                //当前记录所属公司
                let _thisBelongsCompany = item.BelongsCompany;

                //查找有无该公司的权限限定，有的话，只有一个,API接口返回时已经做了权限计算了
                // user - 表  -公司 -时间
                let findApiRecord = findRegulationsList.filter((ele, index) => ele.company == _thisBelongsCompany);
                if (findApiRecord && findApiRecord.length > 0) {
                  let _currentRecord = findApiRecord[0];
                  let itemCreated: Date = new Date(item.Created);
                  let beginTime: Date = new Date(_currentRecord.setBeginTime + 'Z');
                  let endTime: Date = new Date(_currentRecord.setEndTime + 'Z');
                  if (itemCreated >= beginTime && itemCreated <= endTime) {
                    result.push(item);
                  }
                } else {
                  //若没有找到该公司的配置，尝试获取是否有配置了 所有公司的记录 All
                  let findAllRecord = findRegulationsList.filter((eleAll, index) => eleAll.company == 'All');
                  if (findAllRecord && findAllRecord.length > 0) {
                    let _currentAllRecord = findAllRecord[0];
                    let itemCreated: Date = new Date(item.Created);
                    let beginTime: Date = new Date(_currentAllRecord.setBeginTime + 'Z');
                    let endTime: Date = new Date(_currentAllRecord.setEndTime + 'Z');
                    if (itemCreated >= beginTime && itemCreated <= endTime) {
                      result.push(item);
                    }
                  }
                }
              });
            }
            break;

          //合同、规章申请书权限过滤
          case ListGUID.Petition:
            //合同申请书
            let findContract = dataPermissions.filter((item, index) => item.scopeName == 'ContractPetition');

            if (findContract && findContract.length > 0) {
              configContractPetitionPermission = true;

              allData.forEach(item => {
                //只处理合同申请书
                if (item.ItemBelong == 0) {
                  //当前记录所属公司
                  let _company_code = '';

                  let _company_name = item.sosiki_nm;
                  if (_company_name && _company_name != null && _company_name != '') {
                    //映射表中能找到FL部门
                    let existsItems = AAD_FL_DepartmentsItems.filter((a, b) => a.FLDepartmentName == _company_name);
                    if (existsItems && existsItems.length > 0) {
                      let exItem = existsItems[0];
                      _company_code = exItem.Title.toLowerCase(); //配置表的公司简称
                    }
                  }

                  //查找有无该公司的权限限定，有的话，只有一个,API接口返回时已经做了权限计算了
                  // user - 表  -公司 -时间
                  let findApiRecord = findContract.filter(
                    (ele, index) => ele.company != null && ele.company != undefined && ele.company.toLowerCase() == _company_code
                  );
                  if (findApiRecord && findApiRecord.length > 0) {
                    let _currentRecord = findApiRecord[0];
                    let itemCreated: Date = new Date(item.create_date);
                    let beginTime: Date = new Date(_currentRecord.setBeginTime + 'Z');
                    let endTime: Date = new Date(_currentRecord.setEndTime + 'Z');
                    if (itemCreated >= beginTime && itemCreated <= endTime) {
                      result.push(item);
                    }
                  } else {
                    //若没有找到该公司的配置，尝试获取是否有配置了 所有公司的记录 All
                    let findAllRecord = findContract.filter((eleAll, index) => eleAll.company == 'All');
                    if (findAllRecord && findAllRecord.length > 0) {
                      let _currentAllRecord = findAllRecord[0];
                      let itemCreated: Date = new Date(item.create_date);
                      let beginTime: Date = new Date(_currentAllRecord.setBeginTime + 'Z');
                      let endTime: Date = new Date(_currentAllRecord.setEndTime + 'Z');
                      if (itemCreated >= beginTime && itemCreated <= endTime) {
                        result.push(item);
                      }
                    }
                  }
                }
              });
            }

            //规章申请书
            let findRegulations = dataPermissions.filter((item, index) => item.scopeName == 'RegulationsPetition');

            if (findRegulations && findRegulations.length > 0) {
              configRegulationsPetitionPermission = true;

              allData.forEach(item => {
                //只处理 规章申请书
                if (item.ItemBelong == 1) {
                  //当前记录所属公司

                  let _company_code = '';

                  let _company_name = item.sosiki_nm;
                  if (_company_name && _company_name != null && _company_name != '') {
                    //映射表中能找到FL部门
                    let existsItems = AAD_FL_DepartmentsItems.filter((a, b) => a.FLDepartmentName == _company_name);
                    if (existsItems && existsItems.length > 0) {
                      let exItem = existsItems[0];
                      _company_code = exItem.Title.toLowerCase(); //配置表的公司简称
                    }
                  }

                  //查找有无该公司的权限限定，有的话，只有一个,API接口返回时已经做了权限计算了
                  // user - 表  -公司 -时间
                  let findApiRecord = findRegulations.filter(
                    (ele, index) => ele.company != null && ele.company != undefined && ele.company.toLowerCase() == _company_code
                  );
                  if (findApiRecord && findApiRecord.length > 0) {
                    let _currentRecord = findApiRecord[0];
                    let itemCreated: Date = new Date(item.create_date);
                    let beginTime: Date = new Date(_currentRecord.setBeginTime + 'Z');
                    let endTime: Date = new Date(_currentRecord.setEndTime + 'Z');
                    if (itemCreated >= beginTime && itemCreated <= endTime) {
                      result.push(item);
                    }
                  } else {
                    //TODO：如果用户能完全确认此处不会配置申请书的单独的权限，则这里可以直接添加，优化性能
                    //若没有找到该公司的配置，尝试获取是否有配置了 所有公司的记录 All
                    let findAllRecord = findRegulations.filter((eleAll, index) => eleAll.company == 'All');
                    if (findAllRecord && findAllRecord.length > 0) {
                      let _currentAllRecord = findAllRecord[0];
                      let itemCreated: Date = new Date(item.create_date);
                      let beginTime: Date = new Date(_currentAllRecord.setBeginTime + 'Z');
                      let endTime: Date = new Date(_currentAllRecord.setEndTime + 'Z');
                      if (itemCreated >= beginTime && itemCreated <= endTime) {
                        result.push(item);
                      }
                    }
                  }
                }
              });
            }

            break;
          //案件过滤
          case ListGUID.CaseManagement:
            let caseList = dataPermissions.filter((item, index) => item.scopeName == 'CaseManagement');
            if (caseList && caseList.length > 0) {
              configCaseManagementPermission = true;
              allData.forEach(item => {
                //当前记录所属公司
                let _thisBelongsCompany = item.BelongsCompany;
                let needSecrecy = item.NeedSecrecy;
                if (needSecrecy == '否') {
                  //如果不保密，所有人可见
                  result.push(item);
                } else {
                  //查找有无该公司的权限限定，有的话，只有一个,API接口返回时已经做了权限计算了
                  // user - 表  -公司 -时间
                  let findApiRecord = caseList.filter((ele, index) => ele.company == _thisBelongsCompany);
                  if (findApiRecord && findApiRecord.length > 0) {
                    let _currentRecord = findApiRecord[0];
                    let itemCreated: Date = new Date(item.Created);
                    let beginTime: Date = new Date(_currentRecord.setBeginTime + 'Z');
                    let endTime: Date = new Date(_currentRecord.setEndTime + 'Z');
                    if (itemCreated >= beginTime && itemCreated <= endTime) {
                      result.push(item);
                    }
                  } else {
                    //若没有找到该公司的配置，尝试获取是否有配置了 所有公司的记录 All
                    let findAllRecord = caseList.filter((eleAll, index) => eleAll.company == 'All');
                    if (findAllRecord && findAllRecord.length > 0) {
                      let _currentAllRecord = findAllRecord[0];
                      let itemCreated: Date = new Date(item.Created);
                      let beginTime: Date = new Date(_currentAllRecord.setBeginTime + 'Z');
                      let endTime: Date = new Date(_currentAllRecord.setEndTime + 'Z');
                      if (itemCreated >= beginTime && itemCreated <= endTime) {
                        result.push(item);
                      }
                    }
                  }
                }
              });
            }
            break;
          default:
            break;
        }
      }
    }

    //未配置合同列表
    if (!configStandingBookPermission && listguid == ListGUID.StandingBook) {
      if (isFW) {
        return allData;
      } else {
        return []; //
      }
    }

    //未配置 规章制度
    if (!configRegulationsPermission && listguid == ListGUID.Regulations) {
      if (isFW) {
        return allData;
      } else {
        return []; //
      }
    }

    //未配置过合同申请书
    if (!configContractPetitionPermission && listguid == ListGUID.Petition) {
      allData.forEach(item => {
        if (item.ItemBelong == 0) {
          //1-9号玉梅姐核实法务部门不受本人看本人限制，部门看部门，法务部就是看所有
          if (isFW) {
            result.push(item);
          } else {
            //非法务、按照规则来
            //如果没配过申请书的权限，则只能看自己创建的记录 并且部长能看本部的
            if (isLeader) {
              //部长能看本部门的

              let mdep = item.sosiki_nm;
              if (mdep && mdep != null && mdep != '') {
                //映射表中能找到FL部门
                let existsItems = mapFLDepartments.filter((a, b) => a.FLDepartmentName == mdep);
                if (existsItems && existsItems.length > 0) {
                  result.push(item);
                }
              }
            } else {
              //不是部长，只能看自己的
              let userName = currentUser.Title;
              let userEmail = currentUser.Email;
              if (userName && userEmail && userName != '' && userEmail != '') {
                let userCodeArr = userEmail.split('@');
                if (userCodeArr && userCodeArr.length > 1) {
                  let userCode = userCodeArr[0].toLowerCase();
                  let itemUserCode = `${item.apply_user_code}`.toLowerCase();
                  let itemUserName = `${item.apply_user_nm}`.toLowerCase();
                  itemUserName = itemUserName.replace(/\s/g, '');
                  if (userName == itemUserName && userCode == itemUserCode) {
                    result.push(item);
                  }
                }
              }
            }
          }
        }
      });
    }
    //未配置过规章申请书
    if (!configRegulationsPetitionPermission && listguid == ListGUID.Petition) {
      allData.forEach(item => {
        if (item.ItemBelong == 1) {
          result.push(item); //如果没配过规章申请书的权限，全员可见
        }
      });
    }

    //未配置 案件管理
    if (!configCaseManagementPermission && listguid == ListGUID.CaseManagement) {
      if (isCaseLeader) {
        

        
        //当前用户是 法务部，并且未配置案件管理的任何数据权限时，按照默认规则，只能看非保密的或者是受理担当是自己的
allData.forEach(item=>{
result.push(item);

});
       
      } else {
        //当前用户非法务部长、副部长、科长，并且未配置案件管理的任何数据权限时，按照默认规则，只能看非保密的
        //找所有否的记录
        allData.forEach(item => {
        
    
          let NeedSecrecy = item.NeedSecrecy;
          let currentUserIsAcceptor: boolean = false;
          let Acceptor = item.Acceptor;
          if (Acceptor) {
            let arrAcceptors = Acceptor.split(';');
            if (arrAcceptors.length > 0) {
              let compName = currentUser.Id + '#' + currentUser.Title;
              for (let accItem = 0; accItem < arrAcceptors.length; accItem++) {
                const u = arrAcceptors[accItem];
                if (u == compName) {
                  currentUserIsAcceptor = true;
                  break;
                }
              }
            }
          }
          if (NeedSecrecy == '否' || currentUserIsAcceptor) {
            result.push(item);
          }


        });
      }
    }

    return result;
  }

  //判断是否为法务部
  public static async _isLegalDepartment(): Promise<boolean> {
    let currentUser = await Api._getcurrentUser();
    let p1 = await Api.GetUserProperties(currentUser.Email);
    let vDep = '';
    let props = p1.UserProfileProperties;
    if (props && props.length > 0) {
      for (let i = 0; i < props.length; i++) {
        const element = props[i];
        if (element.Key == 'Department') {
          vDep = element.Value;
          break;
        }
      }
    }
    return vDep == '法务部' || vDep == '法務部';
  }

  // 通过list 查询文档库
  public static async _getListFileData({ ListGUID = '' }): Promise<any> {
    return await sp.web.lists.getById(ListGUID).items.select('*').expand('File').getAll();
  }

  public static async testget({ ListGUID = '' }) {
    var items = await sp.web.lists.getById(ListGUID).get();
    
  }

  // 查询文档库指定文件夹下的所有文件
  public static async _getLibraryFileData({ ListGUID = '', searchStr = '', Skip = 0, Top = 4999,  }): Promise<any> {
    if (searchStr) {
      return await sp.web.lists.getById(ListGUID).items.top(1000).select('FSObjType', 'Folder/ItemCount', 'FileRef').expand("Folder").getAll();
      // return await sp.web.lists
      //   .getById(ListGUID)
      //   .items.select('*').top(Top)
      //   .expand('File', 'File/Properties')
      //   .filter("substringof('" + searchStr + "',FileRef) and FSObjType eq 0") //FSObjType 0为文件 1为文件夹
      //   .skip(Skip).getAll();
    } else {
      return await sp.web.lists.getById(ListGUID).items.top(1000).select('FSObjType', 'Folder/ItemCount', 'FileRef').expand("Folder").getAll();
      // return await sp.web.lists
      //   .getById(ListGUID)
      //   .items.select('*').top(Top)
      //   .expand('File', 'File/Properties')
      //   .filter('FSObjType eq 0') //FSObjType 0为文件 1为文件夹
      //   .skip(Skip).getAll();
    }
  }

  //查询整张表  ListTitle:List，Select:需要查询的列，Top:取前几行,Filter:Where条件，Orderby:排序条件，Asc:正序或倒序，skip:分页
  public static async _getListData({
    ListGUID = ''
    // Select = '',
    // Top = 0,
    // Filter = '',
    // Orderby = 'Created',
    // Asc = true,
    // Page = false,
    // Skip = 0
  }): Promise<any> {
    try {
      // return await sp.web.lists.getByTitle(ListTitle).items.top(Top).select(Select).filter(Filter).orderBy(Orderby, Asc).skip(Skip).get();
      return await sp.web.lists.getById(ListGUID).items.getAll();
    } catch (e) {
      
    }
  }

  //查询具体的List item
  public static async _getListDetail({ ListTitle = '', Select = '', ItemId = 0 }): Promise<any> {
    try {
      return await sp.web.lists.getByTitle(ListTitle).items.getById(ItemId).select(Select).get();
    } catch (e) {
      
    }
  }

  //查询List item的附件
  public static async _getListItemFiles({ ListTitle = '', ItemId = 0 }): Promise<any> {
    try {
      return await sp.web.lists.getByTitle(ListTitle).items.getById(ItemId).attachmentFiles.get();
    } catch (e) {
      
    }
  }

  //删除附件,filename为string类型是单个或string[]类型为批量
  public static async _deleteMultiple({ ListTitle = '', ItemId = 0, FileName }) {
    try {
      const z = await sp.web.lists.getByTitle(ListTitle).items.getById(ItemId).attachmentFiles.deleteMultiple(FileName);
    } catch (e) {
      
    }
  }

  //删除附件并移动至回收站,filename为string类型是单个或string[]类型为批量
  public static async _recycle({ ListTitle = '', ItemId = 0, FileName = '' }) {
    try {
      const z = await sp.web.lists.getByTitle(ListTitle).items.getById(ItemId).attachmentFiles.recycleMultiple(FileName);
    } catch (e) {
      
    }
  }

  //增加List item
  public static async _saveaddData({ ListName = '', Obj = {} }): Promise<any> {
    try {
      return await sp.web.lists.getByTitle(ListName).items.add(Obj);
    } catch (e) {
      
    }
  }

  //修改List item
  public static async _saveupdateData({ ListName = '', ItemId = 1, Obj = {} }): Promise<any> {
    try {
      return await sp.web.lists.getByTitle(ListName).items.getById(ItemId).update(Obj);
    } catch (e) {
      
    }
  }

  //删除List item
  public static async _deleteData({ ListName = '', ItemId = 1 }): Promise<any> {
    try {
      let name = GuidName.filter(i => i.name === ListName);
      if(name.length > 0) {
        dynamicsService.changeData({ListGUID: name[0].guid})
      }
      return await sp.web.lists.getByTitle(ListName).items.getById(ItemId).delete();
    } catch (e) {
      
    }
  }

  //sharepoint全局搜索
  public static async _search({ Querytext = '', Page = 1, RowLimit = 10, EnableInterleaving = true }): Promise<any> {
    try {
      let currentResults: SearchResults = null;
      const q = SearchQueryBuilder(Querytext).rowLimit(RowLimit);
      const results = await sp.search(q);
      currentResults = results;
      return await currentResults.getPage(Page);
    } catch (e) {
      
    }
  }

  //读取文件
  public static async _getFileByServerRelativeUrl({ Url = '', Category = 'Blob' }) {
    try {
      if (Category == 'Blob') {
        const blob: Blob = await sp.web.getFileByServerRelativeUrl(Url).getBlob();
        return blob;
      } else if (Category == 'ArrayBuffer') {
        const buffer: ArrayBuffer = await sp.web.getFileByServerRelativeUrl(Url).getBuffer();
        return buffer;
      } else if (Category == 'Json') {
        const json: any = await sp.web.getFileByServerRelativeUrl(Url).getJSON();
        return json;
      } else {
        const file = await sp.web.getFileByUrl(Url); //此方法支持从共享链接或绝对 url 打开文件。该文件必须位于您试图从中打开该文件的站点中。
        return file;
      }
    } catch (e) {
      
    }
  }

  //文件上传 file：文件，Url:上传地址
  public static async _addfiles(file: File, Url = '', Title = '', OtherField = '') {
    try {
      // you can adjust this number to control what size files are uploaded in chunks
      if (file.size <= 10485760) {
        const f0 = await sp.web.getFolderByServerRelativeUrl(Url).files.add(file.name, file, true);
        if (Title != '' && OtherField != '') {
          const item = await f0.file.getItem();
          await item.update({
            Title: Title,
            OtherField: OtherField
          });
        }
        return true;
      } else {
        const f1 = await sp.web.getFolderByServerRelativeUrl(Url).files.addChunked(
          file.name,
          file,
          data => {
            
          },
          true
        );
        if (Title != '' && OtherField != '') {
          const item = await f1.file.getItem();
          await item.update({
            Title: Title,
            OtherField: OtherField
          });
        }
        return true;
      }
    } catch (e) {
      
      return false;
    }
  }

  //更新文件
  public static async _setContentChunked(file: File, Url) {
    try {
      return await sp.web.getFileByServerRelativeUrl(Url).setContentChunked(file);
    } catch (e) {
      
    }
  }

  //移动文件
  public static async _moveTo({ Url, NewUrl }) {
    try {
      await sp.web.getFileByServerRelativePath(Url).moveTo(NewUrl);
    } catch (e) {
      
    }
  }

  //复制文件
  public static async _copyTo({ Url, NewUrl, ShouldOverWritr = false }) {
    try {
      await sp.web.getFileByServerRelativePath(Url).copyTo(NewUrl, ShouldOverWritr);
    } catch (e) {
      
    }
  }

  //删除文件
  public static async _deletefile(filename) {
    try {
      const exists = await sp.web.rootFolder.files.getByName(filename).exists(); //判断文件是否存在
      if (exists) {
        await sp.web.rootFolder.files.getByName(filename).delete();
        return true;
      } else {
        return false;
      }
    } catch (e) {
      
    }
  }

  //按文件夹名称从集合中获取文件夹实例
  public static async _getfolders(FolderName) {
    try {
      return await sp.web.folders.getByName(FolderName)();
    } catch (e) {
      
    }
  }

  public static async _getFolderByServerRelativePath(FolderName) {
    try {
      return await sp.web.getFolderByServerRelativePath(FolderName).files();
    } catch (e) {
      
    }
  }

  /**
   * 根据列表的GUID获取列表的所有数据
   *
   *  @param ListGUID 列表的GUID
   *  @param Select 需要查询的列
   *  @param Top 取前几行
   *  @param Filter Where条件
   *  @param Orderby 排序条件
   *  @param Asc 正序或倒序
   *  @param skip 分页
   *  @returns 列表数据
   */
  public static async GetListItemsByListGUID(
    ListGUID = '',
    Select = '',
    Top = 0,
    Filter = '',
    Orderby = 'Created',
    Asc = true,
    Page = false,
    Skip = 0
  ): Promise<any> {
    try {
      return sp.web.lists.getById(ListGUID).items.top(Top).select(Select).filter(Filter).orderBy(Orderby, Asc).skip(Skip).get();
    } catch (e) {
      
    }
  }


  //删除附件并移动至回收站,filename为string类型是单个或string[]类型为批量
  public static async RecycleFileByListGUIDItemId({ ListGUID = '', ItemId = 0, FileName = '' }) {
    try {
      const z = await sp.web.lists.getById(ListGUID).items.getById(ItemId).attachmentFiles.recycleMultiple(FileName);
    } catch (e) {
      
    }
  }

  public static async RecycleFileByListGUIDItemIdSafe({ ListGUID = '', ItemId = 0, FileName = '' }) {
    if (FileName != '') {
      try {
        var allFile = await sp.web.lists.getById(ListGUID).items.getById(ItemId).attachmentFiles.get();
        
        if (allFile.length > 0) {
          allFile.forEach(async element => {
            if (element.FileName.indexOf(FileName) > -1) {
              var z = await this.RecycleFileByListGUIDItemId({ ListGUID, ItemId, FileName });
            }
          });
        }
      } catch (e) {
        
      }
    }
  }

  /**
   * 根据列表的GUID，列表项的Id获取列表条目数据
   *
   *  @param ListGUID 列表的GUID
   *  @param ItemId 列表ItemId
   *  @returns 获取的ListItem对象
   */
  public static async GetListItemById({ ListGUID = '', ItemId = 0 }): Promise<any> {
    try {
      return await sp.web.lists.getById(ListGUID).items.getById(ItemId).get();
    } catch (e) {
      
    }
  }

  /**
   * 给ListItem添加附件
   *
   *  @param ListGUID 列表的GUID
   *  @param ItemId ItemId
   *  @param FileName 文件名称
   *  @param File 文件内容
   *  @returns 添加后的ListItem对象
   */
  public static async AddItemAttachment({ ListGUID = '', ItemId = 0, FileName = '', File = '' }): Promise<any> {
    try {
      return await sp.web.lists.getById(ListGUID).items.getById(ItemId).attachmentFiles.add(FileName, File);
    } catch (e) {
      
    }
  }

  public static async AddItemAttachmentSafe({ ListGUID = '', ItemId = 0, FileName = '', File = '' }): Promise<any> {
    //先删除之前的附件
    await this.RecycleFileByListGUIDItemIdSafe({ ListGUID, ItemId, FileName });
    try {
      return await sp.web.lists.getById(ListGUID).items.getById(ItemId).attachmentFiles.add(FileName, File);
    } catch (e) {
      
    }
  }

  /**
   * 添加ListItem
   *  @param ListGUID 列表的GUID
   *  @param Obj item实体对象
   *  @returns 添加后的ListItem数据
   */
  public static async AddItemByListGUID({ ListGUID = '', Obj = {} }): Promise<any> {
    try {
      let test1 = await sp.web.lists.getById(ListGUID).items;
      let result = test1.add(Obj);
      return result;
    } catch (e) {
      
    }
  }

  //更新Item
  public static async UpdateItemByListGUID({ ListGUID = '', ItemId = 0, Obj = {} }): Promise<any> {
    try {
      return await sp.web.lists.getById(ListGUID).items.getById(ItemId).update(Obj);
    } catch (e) {
      
    }
  }

  /**
   * 根据CAML语句获取列表项Item
   *
   *  @param ListGUID 列表的GUID
   *  @param CAMLQuery CamlQuery对象
   *  @returns 列表项数据 ListItem
   */
  public static async GetListItemsByCAMLQuery(ListGUID = '', CAMLQuery: ICamlQuery): Promise<any> {
    try {
      return sp.web.lists.getById(ListGUID).getItemsByCAMLQuery(CAMLQuery);
    } catch (e) {
      
    }
  }

  /**
   * 根据itemid获取附件
   *
   *  @param ListGUID 列表的GUID
   *  @param CAMLQuery CamlQuery对象
   *  @returns 列表项数据 ListItem
   */
  public static async _getListItemFilesByGUID({ ListGUID = '', ItemId = 0 }): Promise<any> {
    try {
      return await sp.web.lists.getById(ListGUID).items.getById(ItemId).attachmentFiles.get();
    } catch (e) {
      
    }
  }

  //根据guid查询数据
  public static async _getModel({
    Guid = '',
    Top = 0,
    Filter = '',
    Orderby = 'Created',
    Asc = true,
    Skip = 0,
    Select = '*'
  }): Promise<any> {
    try {
      if (Asc) {
        return await sp.web.lists.getById(Guid).items.top(Top).filter(Filter).orderBy(Orderby, Asc).skip(Skip).select(Select).getAll();
      } else {
        return await (await sp.web.lists.getById(Guid).items.top(Top).filter(Filter).orderBy(Orderby, Asc).skip(Skip).getAll()).reverse();
      }
    } catch (e) {
      
    }
  }
  public static async _getPagedNext({ Guid = '', Top = 5000, select = "", Filter = '', Orderby = 'Created', Asc = true, Skip = 0 }): Promise<any> {
    try {
      return await sp.web.lists.getById(Guid).items.filter(Filter).select(select).orderBy(Orderby, Asc).skip(Skip).getAll(Top);
    } catch (e) {
      
    }
  }
  //根据guid查询2000数据 hasNext == true 表示有下一页数据
  public static async _getPaged({ Guid, PageSize = 0, PageIndex = 0 ,FilterL = []}): Promise<any> {
    try {
      // return await sp.web.lists.getById(Guid).items.filter(Filter).select(select).orderBy(Orderby, Asc).skip(Skip).getAll(Top);
      // var dbName = '';
      // 获取权限需要的数据
      let currentUser = await Api._getcurrentUser()
      let currentEmail = currentUser.Email;
      // 当前邮箱
      // let p1 = await Api.GetUserProperties(currentEmail);
      currentUser = JSON.stringify(currentUser)
      // p1 = JSON.stringify(p1)
      // 所有AAD用户  AADUsers
      let jsonAADUsers = sessionStorage.getItem('AADUsers');
      let sPermission = sessionStorage.getItem('userDataPermissions');
      // 
      let AAD_FL_DepartmentsItems = await Api._getModel({ Guid: ListGUID.FLAD });
      AAD_FL_DepartmentsItems = JSON.stringify(AAD_FL_DepartmentsItems)

      let FilterLList = JSON.stringify(FilterL)

      // 调用接口
      let data = {
        currentUser: currentUser,
        // currentUser: "",
        // UserProfileProperties: p1,
        // UserProfileProperties: "",
        // AADUsers: jsonAADUsers,
        // AADUsers: "",
        // userDataPermissions: sPermission,
        // userDataPermissions: "",
        // AAD_FL_DepartmentsItems: AAD_FL_DepartmentsItems,
        // AAD_FL_DepartmentsItems: "",
        ListGUID: Guid ? Guid : '',
        PageSize: PageSize,
        PageIndex: PageIndex,
        Filter:FilterLList
      } 
      // let data = {
      //   currentUser: "",
      //   UserProfileProperties: "",
      //   AADUsers: "",
      //   userDataPermissions: "",
      //   AAD_FL_DepartmentsItems: "",
      //   ListGUID: Guid,
      //   PageSize: PageSize,
      //   PageIndex: PageIndex,
      //   Filter:FilterLList
      // } 

      let getList = await dynamicsService.getList(data)

      // 
      return getList

      //return  indexDs.getTableData(dbName);
    } catch (e) {
      
    }
  }
  public static async _getPaged2({ Guid, PageSize = 0, PageIndex = 0 ,FilterL = []}): Promise<any> {
    try {
      // return await sp.web.lists.getById(Guid).items.filter(Filter).select(select).orderBy(Orderby, Asc).skip(Skip).getAll(Top);
      // var dbName = '';
      // 获取权限需要的数据
      // let currentUser = await Api._getcurrentUser()
      // let currentEmail = currentUser.Email;
      // // 当前邮箱
      // let p1 = await Api.GetUserProperties(currentEmail);
      // currentUser = JSON.stringify(currentUser)
      // p1 = JSON.stringify(p1)
      // // 所有AAD用户  AADUsers
      // let jsonAADUsers = sessionStorage.getItem('AADUsers');
      // let sPermission = sessionStorage.getItem('userDataPermissions');
      // // 
      // let AAD_FL_DepartmentsItems = await Api._getModel({ Guid: ListGUID.FLAD });
      // AAD_FL_DepartmentsItems = JSON.stringify(AAD_FL_DepartmentsItems)

      let FilterLList = JSON.stringify(FilterL)

      // 调用接口
      let data = {
        // currentUser: currentUser,
        currentUser: "",
        // UserProfileProperties: p1,
        UserProfileProperties: "",
        // AADUsers: jsonAADUsers,
        AADUsers: "",
        // userDataPermissions: sPermission,
        userDataPermissions: "",
        // AAD_FL_DepartmentsItems: AAD_FL_DepartmentsItems,
        AAD_FL_DepartmentsItems: "",
        ListGUID: Guid ? Guid : '',
        PageSize: PageSize,
        PageIndex: PageIndex,
        Filter:FilterLList
      } 
      // let data = {
      //   currentUser: "",
      //   UserProfileProperties: "",
      //   AADUsers: "",
      //   userDataPermissions: "",
      //   AAD_FL_DepartmentsItems: "",
      //   ListGUID: Guid,
      //   PageSize: PageSize,
      //   PageIndex: PageIndex,
      //   Filter:FilterLList
      // } 

      let getList = await dynamicsService.getListAll(data)

      
      return getList

      //return  indexDs.getTableData(dbName);
    } catch (e) {
      
    }
  }
  public static async _getPaged3({ Guid, PageSize = 0, PageIndex = 0 ,FilterL = [], search}): Promise<any> {
    try {
      // 获取权限需要的数据
      let currentUser = await Api._getcurrentUser()
      currentUser = JSON.stringify(currentUser)
      // 

      let FilterLList = JSON.stringify(FilterL)

      // 调用接口
      let data = {
        currentUser: currentUser,
        ListGUID: Guid ? Guid : '',
        PageSize: PageSize,
        PageIndex: PageIndex,
        Filter:FilterLList,

      } 


      let getList = await dynamicsService.getAllFileQuery({data,  search})
      return getList
    } catch (e) {
      
    }
  }
  // 申请书--查数据
  public static async _getPaged1({ Guid = '', Top = 1000, Filter = '', Orderby = 'Created', Asc = true, Skip = 0 }): Promise<any> {
    try {


      // if (Attributename == "规定申请书") {
      //   select = "circulation_department", "advance_notificate_time", "duration_of_contract", "decision_flag", "board_meeting", "operation_meeting", "mediate_or_single_decision", "discuss_depart", "reason_without_ddq", "ddq_flag", "decision_content_3", "decision_content_2", "expect_decide_date", "secrecy", "sinsei_code", "sosiki_nm", "apply_user_nm", "decision_std", "sign_contract", "for_up_affairs", "contract_confirm", "company_name", "apply_date", "update_time", "filename", "company_code", "company_name", "contract_no"
      // } else if (Attributename == "合同") {

      //   select = "Title", "Created", "Author", "ReviewOnID", "Other", "FileAddress", "RuleNumber", "ContractLawyerReview", "HasReviewOpinion", "Qualifications", "ContactEditNature", "ContractSignificance", "ContractDeadline", "ContractNature", "Contractualproblems", "Language", "BelongsDepartment", "BelongsCompany", "RelierName", "Counterparty", "Our", "Keyword2", "Keyword1", "ContractName", "LastAnswerTime", "AcceptTime",

      // } else if (Attributename == "规章") {

      //   select = "Created", "Author", "ReviewOn", "RuleNumber", "Other", "LawyerReview", "HasReviewOpinion", "ModifyNature", "RegulationsCatalog", "Question", "Language", "RelierName", "BelongsCompany", "VersionNum", "RegulationsNum", "RegulationsName", "LastAnswerTime", "AcceptTime", "Title",

      // } else if (Attributename == "案件") {

      //   select = "Created", "Author", "Acceptor", "Other", "NeedSecrecy", "HasLawyer", "OpinionBook", "CaseType", "RelierName", "BelongsCompany", "CaseSummary", "CaseName", "LastAnswerTime", "AcceptTime", "Title",

      // } else if(Attributename == "合同申请书"){
      //   select = "Created",
      // }


      return await sp.web.lists.getById(Guid).items.filter(Filter).select("circulation_department", "advance_notificate_time", "duration_of_contract", "decision_flag", "board_meeting", "operation_meeting", "mediate_or_single_decision", "discuss_depart", "reason_without_ddq", "ddq_flag", "decision_content_3", "decision_content_2", "expect_decide_date", "secrecy", "sinsei_code", "sosiki_nm", "apply_user_nm", "decision_std", "sign_contract", "for_up_affairs", "contract_confirm", "company_name", "apply_date", "update_time", "filename", "company_code", "company_name", "contract_no").orderBy(Orderby, Asc).skip(Skip).getAll(Top);
    } catch (e) {
      
    }
  }


  //根据guid获取count
  public static async _getCount({ Guid = '' }): Promise<any> {
    try {
      return await sp.web.lists.getById(Guid).select('ItemCount').get();
    } catch (e) {
      
    }
  }

  //根据guid的编号模糊查询文档名称
  public static async _getUser(): Promise<any> {
    try {
      return await pnp.sp.site.rootWeb.siteUsers.get();
    } catch (e) {
      
    }
  }

  //根据guid的编号模糊查询文档名称
  public static async _getModelli({ Guid = '', Top = 1, Filter = '' }): Promise<any> {
    try {
      return await sp.web.lists.getById(Guid).items.top(Top).filter(Filter).get();
    } catch (e) {
      
    }
  }

  //根据guid添加
  public static async _saveaddDataGuid({ Guid = '', Obj = {} }): Promise<any> {
    try {
      dynamicsService.changeData({ListGUID: Guid})
      return await sp.web.lists.getById(Guid).items.add(Obj);
    } catch (e) {
      
    }
  }
  //根据guid修改
  public static async _updateData({ Guid = '', ItemId = 1, Obj = {} }): Promise<any> {
    try {
      dynamicsService.changeData({ListGUID: Guid})
      return await sp.web.lists.getById(Guid).items.getById(ItemId).update(Obj);
    } catch (e) {
      
    }
  }
  //根据文档编号获取文档名称----
  public static async _getfilename({ Guid = '', Select = 'File', expand = 'File' }): Promise<any> {
    try {
      return await sp.web.lists.getById(Guid).items.select(Select).expand(expand).get();
    } catch (e) {
      
    }
  }
  //其他文件自定义属性获取 TODO，待完善参数
  public static async getFilesOtherField(Url = '', Field = '') {
    var items = await sp.web.getFolderByServerRelativeUrl(Url).files();
    var itemFiles = await sp.web.getFolderByServerRelativeUrl(Url).files.expand('ListItemAllFields', 'Author').get();
    var listGUID = 'd5e65b93-83db-4606-b497-8f9e7c7fe21e';
    var pp = await sp.web.lists
      .getById(listGUID)
      .items.select('File', 'File/Name', 'FileLeafRef', 'Description')
      .expand('File', 'File/Properties')
      .filter('FSObjType eq 0') //只查文件  1的话盲猜只查文件夹
      .get();
    

    return pp;
  }

  //根据文档编号获取文档名称----
  public static async _getfile({ Name = '文档中心', filter = 'FSObjType eq 0' }): Promise<any> {
    try {
      let searchStr = 1111;
      return await sp.web.lists
        .getByTitle(Name)
        .items.select('File', 'File/Name', 'FileLeafRef')
        .expand('File', 'File/Properties')
        .filter(filter)
        .get();
    } catch (e) {
      
    }
  }
  //根据文档编号获取文档名称----
  public static async _getfileByGUID({ Guid = '', filter = 'FSObjType eq 0' }): Promise<any> {
    try {
      let searchStr = 1111;
      return await sp.web.lists
        .getById(Guid)
        .items.select('File', 'File/Name', 'FileLeafRef', 'File/UniqueId', 'UniqueId')
        .expand('File', 'File/Properties')
        .getAll(5000);
    } catch (e) {
      
    }
  }
  //根据guid获取附件
  public static async _getListFiles({ Guid = '', ItemId = 0 }): Promise<any> {
    try {
      return await sp.web.lists.getById(Guid).items.getById(ItemId).attachmentFiles.get();
    } catch (e) {
      
    }
  }

  public static _initAADUsers() {
    dynamicsService.getAADUsers();
  }

  //获取用户详情
  public static async _getcurrentUser(): Promise<any> {
    try {
      return await sp.web.currentUser();
    } catch (e) {
      
    }
  }

  public static async GetUserById(id): Promise<any> {
    try {
      return await sp.web.getUserById(id).get();
    } catch (e) {
      
    }
  }
  
  //根据邮箱获取人员信息
  public static async GetUserByEmail(email): Promise<any> {
    try {
      var res = await sp.web.siteUsers.getByEmail(email)();
      return res;
    } catch (e) {
      
    }
  }

  //根据邮箱获取人员信息
  public static async GetUserProperties(email: string): Promise<any> {
    var user = await Api.GetUserByEmail(email);
    return await pnp.sp.profiles.getPropertiesFor(user.LoginName);
    // var allProp = propp.UserProfileProperties;
    // 
  }
  //   ByEmail2(email): Promise<any> {
  //     try {
  //       var res = await sp.web.siteUsers.getByEmail(email)();
  //       return res;
  //     } catch (e) {
  //       
  //     }
  //   }

  //获取站点所有用户
  public static async siteUsers(): Promise<any> {
    try {
      return await sp.web.siteUsers();
    } catch (e) {
      
    }
  }

  //根据GUID修改List item
  public static async _saveupdateDataByGuid({ ListGUID = '', ItemId = 1, Obj = {} }): Promise<any> {
    try {
      return await sp.web.lists.getById(ListGUID).items.getById(ItemId).update(Obj);
    } catch (e) {
      
    }
  }
  //修改List item
  public static async _saveEditData({ Guid = '', ItemId = 1, Obj = {} }): Promise<any> {
    try {
      return await sp.web.lists.getById(Guid).items.getById(ItemId).update(Obj);
    } catch (e) {
      
    }
  }

  //删除附件,filename为string类型是单个或string[]类型为批量 guid
  public static async _deleteMultipleGuid({ Guid = '', ItemId = 0, FileName }) {
    try {
      const z = await sp.web.lists.getById(Guid).items.getById(ItemId).attachmentFiles.deleteMultiple(FileName);
    } catch (e) {
      
    }
  }

  //查询List item的附件
  public static async _getListItemFilesGuid({ Guid = '', ItemId = 0 }): Promise<any> {
    try {
      return await sp.web.lists.getById(Guid).items.getById(ItemId).attachmentFiles.get();
    } catch (e) {
      
    }
  }

  public static async _getSearchData({
    guid = '',
    Select = '',
    Top = 0,
    Filter = '',
    Orderby = 'Created',
    Asc = true,
    Page = false,
    Skip = 0
  }): Promise<any> {
    try {
      return await sp.web.lists.getById(guid).items.top(Top).filter(Filter).orderBy(Orderby, Asc).getAll();
    } catch (e) {
      
    }
  }

  public static async _getSearchFolderData({ folders = '', Filter = '' }): Promise<any> {
    try {
      return await sp.web.folders.getByName(folders).folders.filter(Filter).get();
    } catch (e) {
      
    }
  }

  public static async _getSearchFolderFilesData({ folders = '', Filter = '' }): Promise<any> {
    try {
      return await sp.web.folders.getByName(folders).files.filter(Filter).get();
    } catch (e) {
      
    }
  }

  //测试1，获取某个文件夹下所有文件，查询是否有重复的文件
  public static async action1(Url = '', Title = '', OtherField = '') {
    var items = await sp.web.getFolderByServerRelativeUrl(Url).files();
    
    return items;
  }
  public static async getFiles(Url = '') {
    var items = await sp.web.getFolderByServerRelativeUrl(Url).files();
    // 
    return items;
  }
  

  public static async checkAndCreateFolder(relativeUrl: string): Promise<any> {
    //要创建最后别加斜杠
    const folder = await sp.web.getFolderByServerRelativePath(relativeUrl).select('Exists').get();
    if (!folder.Exists) {
      return await sp.web.folders.addUsingPath(relativeUrl);
    }
  }

  ///创建Caml语句   只包含And查询
  public static buildCamlXml(camlParams: CamlParam[], orderBy: CamlOrderBy = null): string {
    //TODO,加上OrderBy
    if (camlParams.length == 0) {
      return '';
    }

    let start: string = `   <View>
                                <Query>
                                    <Where> `;

    if (camlParams.length == 1) {
      let p: CamlParam = camlParams[0];
      let pice = this.buildItemCamlXml(p);
      start += pice;
    } else {
      let pice: string = this.buildItemCamlXml(camlParams[0]);
      for (let i = 1; i < camlParams.length; i++) {
        const currentItem = camlParams[i];
        let _thisXml = this.buildItemCamlXml(currentItem);
        pice = `<${CAMLFilter.And}>${pice}${_thisXml}</${CAMLFilter.And}>`;
      }
      start += pice;
    }
    let replaceStr = '';
    if (orderBy != null) {
      replaceStr = `<OrderBy>
                        <FieldRef Name='${orderBy.FieldName}' Ascending='${orderBy.Ascending}' />
                    </OrderBy>`;
    }
    let end: string = `
                                    </Where>
                                    ${replaceStr}
                                </Query>   
                            </View> `;
    return start + end;
  }
  ///创建Caml语句   只包含Or查询
  public static buildCamlXmlOr(camlParams: CamlParam[], orderBy: CamlOrderBy = null): string {
    //TODO,加上OrderBy
    if (camlParams.length == 0) {
      return '';
    }

    let start: string = `   <View>
                                <Query>
                                    <Where> `;

    if (camlParams.length == 1) {
      let p: CamlParam = camlParams[0];
      let pice = this.buildItemCamlXml(p);
      start += pice;
    } else {
      let pice: string = this.buildItemCamlXml(camlParams[0]);
      for (let i = 1; i < camlParams.length; i++) {
        const currentItem = camlParams[i];
        let _thisXml = this.buildItemCamlXml(currentItem);
        pice = `<${CAMLFilter.Or}>${pice}${_thisXml}</${CAMLFilter.Or}>`;
      }
      start += pice;
    }
    let replaceStr = '';
    if (orderBy != null) {
      replaceStr = `<OrderBy>
                        <FieldRef Name='${orderBy.FieldName}' Ascending='${orderBy.Ascending}' />
                    </OrderBy>`;
    }
    let end: string = `
                                    </Where>
                                    ${replaceStr}
                                </Query>   
                            </View> `;
    return start + end;
  }

  ///创建Caml语句  首页右侧导航
  public static buildCamlXmlForCurrentOperator(camlParamsTime: CamlParam[], camlParamsPerson: CamlParam[]) {
    let start: string = `   <View>
                                  <Query>
                                      <Where> `;
    let pice: string = '';

    if (camlParamsPerson.length == 0) {
      pice = this.buildItemCamlXml(camlParamsTime[0]);
      pice = `<${CAMLFilter.And}>${pice}${this.buildItemCamlXml(camlParamsTime[1])}</${CAMLFilter.And}>`;
    } else {
      if (camlParamsPerson.length == 1) {
        let p: CamlParam = camlParamsPerson[0];
        pice = this.buildItemCamlXml(p);
      } else {
        pice = this.buildItemCamlXml(camlParamsPerson[0]);
        for (let i = 1; i < camlParamsPerson.length; i++) {
          const currentItem = camlParamsPerson[i];
          let _thisXml = this.buildItemCamlXml(currentItem);
          pice = `<${CAMLFilter.Or}>${pice}${_thisXml}</${CAMLFilter.Or}>`;
        }
      }

      pice = `<${CAMLFilter.And}>${pice}${this.buildItemCamlXml(camlParamsTime[0])}</${CAMLFilter.And}>`;
      pice = `<${CAMLFilter.And}>${pice}${this.buildItemCamlXml(camlParamsTime[1])}</${CAMLFilter.And}>`;
    }

    let end: string = `
                                      </Where>                                      
                                  </Query>   
                              </View> `;
    return start + pice + end;
  }

  private static buildItemCamlXml(camlParam: CamlParam): string {
    if (camlParam.CompareType == CAMLCompare.IsNull || camlParam.CompareType == CAMLCompare.IsNotNull) {
      return ` <${camlParam.CompareType}>
                    <FieldRef Name='${camlParam.FieldName}' />
               </${camlParam.CompareType}> `;
    } else {
      return ` <${camlParam.CompareType}>
                    <FieldRef Name='${camlParam.FieldName}'></FieldRef>
                    <Value Type='${camlParam.FieldType}'>${camlParam.FieldValue}</Value>
               </${camlParam.CompareType}> `;
    }
  }

  /**
   * 获取文件夹
   * @param Name 库名（url中的名称）
   * @returns
   */
  public static async getFolder(Name = '') {
    var items = await sp.web.lists.getByTitle(Name).rootFolder.folders();

    return items;
  }

  /**
   * 根据文件夹的id获取目标子文件夹
   * @param Id  UniqueId 唯一id
   * @returns
   */
  public static async getSonFolder(Id = '') {
    var items = sp.web.getFolderById(Id).folders();

    return items;
  }
  /**
   * 根据文件夹的path获取目标子文件夹
   * @param Id  UniqueId 唯一id
   * @returns
   */
   public static async getSonFolder1(path = '') {
    // var items = sp.web.getFolderById(Id).folders();
    var items = sp.web.getFolderByServerRelativePath(path).folders();
    return items;
  }
  /**
   * 根据文件夹id获取该文件夹下的文件
   * @param Id  UniqueId 唯一id
   * @returns
   */
  public static async getFileByFolder(Id) {
    var items = sp.web.getFolderById(Id).files();

    return items;
  }


  //获取文档库中的所有文件夹
  public static async GetSiteDocumentFolder(DocId: string): Promise<any> {
    try {
      return await sp.web.lists.getById(DocId).items.top(1000).select('FSObjType', 'Folder/ItemCount', 'FileRef').expand("Folder").getAll();
    } catch (e) {
      
    }
  }

  public static async getChangeLog(Name){
    try {
      return await sp.web.lists.getByTitle(Name).getChanges({Add: true, ChangeTokenEnd: undefined, ChangeTokenStart: undefined, DeleteObject: true, Update: false, Web: true, Rename: true, Item: true});
    } catch (e) {
      
    }
  }
}
